@echo off
title 完成开机自启动设置 - 需要管理员权限
color 0E

echo.
echo ╔══════════════════════════════════════════════════════════════╗
echo ║                完成开机自启动设置                            ║
echo ╚══════════════════════════════════════════════════════════════╝
echo.

echo 🔧 正在设置Windows开机自启动...

echo.
echo 1️⃣ 创建启动脚本...
set "SCRIPT_PATH=%~dp0start-server-on-boot.bat"
echo @echo off > "%SCRIPT_PATH%"
echo cd /d "%~dp0" >> "%SCRIPT_PATH%"
echo pm2 start backend/server.js --name "neighborhood-help-backend" >> "%SCRIPT_PATH%"
echo pm2 save >> "%SCRIPT_PATH%"

echo.
echo 2️⃣ 创建Windows任务计划...
schtasks /create /tn "NeighborhoodHelpBackend" /tr "%SCRIPT_PATH%" /sc onstart /ru "SYSTEM" /f

if errorlevel 1 (
    echo ❌ 任务计划创建失败！
    echo.
    echo 💡 解决方案：
    echo    1. 右键点击此脚本，选择"以管理员身份运行"
    echo    2. 或者手动运行以下命令（需要管理员权限）：
    echo       schtasks /create /tn "NeighborhoodHelpBackend" /tr "%~dp0start-server-on-boot.bat" /sc onstart /ru "SYSTEM" /f
) else (
    echo ✅ 开机自启动设置成功！
)

echo.
echo 3️⃣ 验证当前服务器状态...
pm2 status neighborhood-help-backend >nul 2>&1
if errorlevel 1 (
    echo 🚀 启动服务器...
    pm2 start backend/server.js --name "neighborhood-help-backend"
    pm2 save
) else (
    echo ✅ 服务器已在运行
)

echo.
echo 📊 当前状态:
pm2 status

echo.
echo 🌐 服务器地址: http://192.168.1.6:3002/api
echo 📱 服务器现在会在开机时自动启动！

echo.
echo 💡 管理命令:
echo   schtasks /query /tn "NeighborhoodHelpBackend" - 查看任务
echo   schtasks /delete /tn "NeighborhoodHelpBackend" /f - 删除任务
echo   pm2 status - 查看服务器状态

echo.
pause
